package com.mx.mg.idempotence.service.impl;

import com.mx.mg.idempotence.common.Constant;
import com.mx.mg.idempotence.common.ResponseCode;
import com.mx.mg.idempotence.exception.ServiceException;
import com.mx.mg.idempotence.service.TokenService;
import com.mx.mg.idempotence.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Auther: ghm
 * @Date: 2021/09/02/16:37
 * @Description:
 */
@Service
public class TokenServiceImpl implements TokenService {
    private static final String TOKEN_NAME = "token";

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 创建token
     *
     * @return
     */
    @Override
    public String createToken() {
        String str = UUID.randomUUID().toString();
        StringBuilder token = new StringBuilder();
        try {
            token.append(Constant.Redis.TOKEN_PREFIX).append(str);
            redisUtil.setEx(token.toString(),token.toString(),30000L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 校验token
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public boolean checkToken(HttpServletRequest request) {

        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)){// header 中不存在 token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)){// parameter 也不存在 token
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }

        if (!redisUtil.exists(token)) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }

        boolean remove = redisUtil.remove(token);
        if (!remove) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }

        return true;
    }
}
